from collections import defaultdict


def is_winning_hand(hand):
    """
    校验普通胡牌牌型
    :param hand: 手牌列表，例如 ['1万', '2万', '3万', '东', '东', '东']
    :return: bool 是否胡牌
    """
    # 按牌型分类
    tiles = defaultdict(list)
    for tile in hand:
        suit = '字牌' if len(tile) == 1 else tile[1]
        tiles[suit].append(tile)

    # 七对子检查
    if _check_seven_pairs(hand):
        return True

    # 普通牌型检查
    return _check_standard_win(tiles)


def _check_seven_pairs(hand):
    """七对子检查"""
    if len(hand) != 14:
        return False

    tile_counts = defaultdict(int)
    for tile in hand:
        tile_counts[tile] += 1

    return all(count == 2 for count in tile_counts.values())


def _check_standard_win(tiles):
    """标准胡牌检查"""
    # 分离将牌和普通牌
    has_pair = False
    for suit in tiles:
        # 字牌需要单独处理
        if suit == '字牌':
            if not _check_honors(tiles[suit]):
                return False
        else:
            # 处理数字牌
            sorted_tiles = sorted(tiles[suit], key=lambda x: int(x[0]))
            pair_removed, pair_found = _remove_pair(sorted_tiles)
            if not _check_normal_suit(pair_removed):
                return False
            if pair_found:
                has_pair = True

    return has_pair


#碰碰胡检查
def _check_peng_peng(tiles):
    """检查是否为碰碰胡"""
    # 字牌必须有2对
    if len(tiles['字牌']) != 4:
        return False

    # 其他牌型必须有3对
    for suit in tiles:
        if suit != '字牌':
            if len(tiles[suit]) % 2 != 0:
                return False
    return True

#清一色检查
def _check_all_color(tiles):
    """检查是否为清一色"""
    # 字牌不能清一色
    if '字牌' in tiles:
        return False

    # 检查其他牌型是否清一色
    for suit in tiles:
        if suit != '字牌':
            if len(set(tile[1] for tile in tiles[suit])) != 1:
                return False
    return True


def _check_honors(honors):
    """检查字牌是否符合条件（必须组成刻子）"""
    count = defaultdict(int)
    for tile in honors:
        count[tile] += 1

    for cnt in count.values():
        if cnt not in (0, 3):
            return False
    return True


def _remove_pair(tiles):
    """尝试移除将牌"""
    for i in range(len(tiles) - 1):
        if tiles[i] == tiles[i + 1]:
            # 找到将牌，移除并检查剩余牌
            new_tiles = tiles[:i] + tiles[i + 2:]
            if _check_normal_suit(new_tiles):
                return new_tiles, True
    return tiles, False


def _check_normal_suit(tiles):
    """检查普通花色（万/条/饼）"""
    if not tiles:
        return True

    # 尝试找刻子
    if len(tiles) >= 3 and tiles[0] == tiles[1] == tiles[2]:
        return _check_normal_suit(tiles[3:])

    # 尝试找顺子
    first = tiles[0]
    next1 = str(int(first[0]) + 1) + first[1]
    next2 = str(int(first[0]) + 2) + first[1]

    if next1 in tiles and next2 in tiles:
        new_tiles = tiles.copy()
        new_tiles.remove(first)
        new_tiles.remove(next1)
        new_tiles.remove(next2)
        return _check_normal_suit(new_tiles)

    return False